#! /bin/bash

# SPDX-FileCopyrightText: © 2024 Tenstorrent Inc.
# SPDX-License-Identifier: GPL-2.0-only

set -e

ttdriver_rel="/mnt/motor/syseng/ttdriver-rel"

opts=$(/usr/bin/getopt -n make-installer -l deploy-motor,help "h" "$@")
eval set -- "$opts"

print_usage() {
    echo "Usage: make-installer --deploy-motor | target-dir"
    echo "--deploy-motor automatically deploys to /mnt/motor."
    echo "Otherwise a target directory must be given."
}

deploy_motor=0

while (($#)); do
    case "$1" in
        -h|--help) print_usage; exit 0;;
        --deploy-motor) deploy_motor=1;;
        --) shift; break;;
    esac
    shift
done

if (( ($deploy_motor && $# > 0) || (!$deploy_motor && $# != 1) )); then
    print_usage
    exit 1
fi

package_version=$(tools/current-version)
archive=$(tools/make-source-release -m)
archive_basename=$(basename "$archive")

if (($deploy_motor)); then
    if [ ! -d "$ttdriver_rel" ]; then
        echo "No access to $ttdriver_rel, is motor mounted?"
        exit 1
    fi

    target="$ttdriver_rel/$package_version"
    mkdir -p "$target"
else
    target="$1"
fi

cp "$archive" "$target/$archive_basename"

install_script="$target/install_ttkmd_$package_version.bash"

cat tools/installer-header.sh > "$install_script"
gzip -cn9 "$archive" >> "$install_script"

chmod a+x "$install_script"

echo "Deployed to $target."
